# OpenGL vs 软件渲染性能测试工具 Makefile

# 编译器设置
CC = gcc
CFLAGS = -Wall -Wextra -O2 -std=c99

# 检测操作系统
UNAME_S := $(shell uname -s)
UNAME_P := $(shell uname -p)

# 根据操作系统配置路径和库
ifeq ($(UNAME_S),Linux)
    # Linux 配置
    ifeq ($(UNAME_P),aarch64)
        # 64 位 ARM
        INCLUDES = -I/usr/lib/aarch64-linux-gnu/sietium/include
        LIBDIRS = -L/usr/lib/aarch64-linux-gnu
    endif
    LIBS = -lX11 -lGL -lm
else ifeq ($(UNAME_S),Darwin)
    # macOS 配置 (XQuartz)
    INCLUDES = -I/opt/X11/include
    LIBDIRS = -L/opt/X11/lib
    LIBS = -lX11 -lGL -lm
endif

# 目标文件
TARGET = x11-glx-test
SOURCE = x11-glx-test.c

# 默认目标
all: $(TARGET)

# 编译规则
$(TARGET): $(SOURCE)
	@echo "正在编译 $(TARGET)..."
	$(CC) $(CFLAGS) $(INCLUDES) $(LIBDIRS) -o $(TARGET) $(SOURCE) $(LIBS)
	@echo "编译完成！"

# 调试版本
debug: CFLAGS += -g -DDEBUG
debug: $(TARGET)
	@echo "调试版本编译完成！"

# 运行程序
run: $(TARGET)
	@echo "启动程序..."
	./$(TARGET)

# 清理编译产物
clean:
	@echo "清理编译文件..."
	rm -f $(TARGET)
	@echo "清理完成！"

# 安装依赖检查
install-deps:
ifeq ($(UNAME_S),Linux)
	@echo "检查 Linux 系统 OpenGL 依赖..."
	@echo "正在检查必要的开发包..."
	@if ! dpkg -l | grep -q libgl1-mesa-dev; then \
		echo "警告: 未找到 libgl1-mesa-dev，请安装:"; \
		echo "  sudo apt update"; \
		echo "  sudo apt install libgl1-mesa-dev libglu1-mesa-dev"; \
	fi
	@if ! dpkg -l | grep -q libx11-dev; then \
		echo "警告: 未找到 libx11-dev，请安装:"; \
		echo "  sudo apt install libx11-dev"; \
	fi
	@if [ -f "/usr/include/GL/gl.h" ] || [ -f "/usr/include/x86_64-linux-gnu/GL/gl.h" ] || [ -f "/usr/include/aarch64-linux-gnu/GL/gl.h" ]; then \
		echo "✓ OpenGL 头文件已找到"; \
	else \
		echo "❌ 未找到 OpenGL 头文件，请安装:"; \
		echo "  sudo apt install mesa-common-dev libgl1-mesa-dev"; \
	fi
	@if [ -f "/usr/include/X11/Xlib.h" ]; then \
		echo "✓ X11 头文件已找到"; \
	else \
		echo "❌ 未找到 X11 头文件，请安装:"; \
		echo "  sudo apt install libx11-dev"; \
	fi
else ifeq ($(UNAME_S),Darwin)
	@echo "检查 macOS XQuartz 安装状态..."
	@if [ ! -d "/opt/X11" ]; then \
		echo "错误: 未找到 XQuartz，请安装 XQuartz:"; \
		echo "  方式1: brew install --cask xquartz"; \
		echo "  方式2: 从 https://www.xquartz.org 下载安装"; \
		exit 1; \
	else \
		echo "XQuartz 已安装！"; \
	fi
else
	@echo "不支持的操作系统: $(UNAME_S)"
endif

# 显示帮助信息
help:
	@echo "可用的 Make 目标:"
	@echo "  all          - 编译程序 (默认)"
	@echo "  debug        - 编译调试版本"
	@echo "  run          - 编译并运行程序"
	@echo "  clean        - 清理编译文件"
	@echo "  install-deps - 检查依赖项"
	@echo "  help         - 显示此帮助信息"
	@echo ""
	@echo "使用示例:"
	@echo "  make         # 编译程序"
	@echo "  make run     # 编译并运行"
	@echo "  make clean   # 清理文件"
	@echo ""
	@echo "当前系统: $(UNAME_S)"
ifeq ($(UNAME_S),Linux)
	@echo "Linux 特定配置:"
	@echo "  头文件路径: $(INCLUDES)"
	@echo "  库文件路径: $(LIBDIRS)"
	@echo "  链接库: $(LIBS)"
else ifeq ($(UNAME_S),Darwin)
	@echo "macOS 特定配置:"
	@echo "  需要安装 XQuartz"
	@echo "  头文件路径: $(INCLUDES)"
	@echo "  库文件路径: $(LIBDIRS)"
	@echo "  链接库: $(LIBS)"
endif

# 防止文件名冲突
.PHONY: all debug run clean install-deps help